package Top101;

import org.w3c.dom.ls.LSInput;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/3/30 15:00
 * BM2 链表内指定区间反转
 */
public class Solution2 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;
        Solution.reverseBetween(node1,2,4);
    }
    static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }

    static class Solution {
        /**
         * @param head ListNode类
         * @param m    int整型
         * @param n    int整型
         * @return ListNode类
         */
        public static ListNode reverseBetween(ListNode head, int m, int n) {
            // write code here
            ListNode res = new ListNode(0);
            res.next = head;
            ListNode pre = res;
            ListNode cur = head;
            for (int i = 1; i < m; i++) {
                pre = cur;
                cur = cur.next;
            }
            for (int i = 0; i < n-m; i++) {
                ListNode tem = cur.next;
                cur.next = tem.next;
                tem.next = pre.next;
                pre.next = tem;
            }
            return res.next;
        }
    }
}
